581. Shortest Unsorted Continuous Subarray

1. Question

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

2. Examples

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

3. Constraints

1 <= nums.length <= 104 -105 <= nums[i] <= 105

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        if (null == nums || nums.length <= 1) {
            return 0;
        }

        int cnt = 0;
        int[] sorted = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            sorted[i] = nums[i];
        }
        Arrays.sort(sorted);

        ArrayList<Integer> integers = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            if (sorted[i] != nums[i]) {
                integers.add(i);
            }
        }

        Integer[] arr = integers.toArray(new Integer[0]);
        Arrays.sort(arr);

        if (0 == arr.length) {
            return 0;
        }

        cnt = Math.max(arr[arr.length - 1] - arr[0] + 1, 0);

        return cnt;
    }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""